package main;

import java.io.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by freewheel on 2016/11/16.
 */
public class DBHelper {

    private static Connection conn;
    private static List<String> tableNames;

    static {
        tableNames = new ArrayList<String>();
        tableNames.add("manufacturer");
        tableNames.add("salesperson");
        tableNames.add("category");
        tableNames.add("part");
        tableNames.add("transaction");
        tableNames = Collections.unmodifiableList(tableNames);
    }

    public static Connection getConnection() {
        if (conn == null) {
            conn = connectToDB();
        }
        return conn;
    }

    public static List<String> getTableNames() {
        return tableNames;
    }

    private static Connection connectToDB() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            try {
                FileReader reader = new FileReader(new File("key.txt"));
                BufferedReader bufferedReader = new BufferedReader(reader);
                String dblink = bufferedReader.readLine();
                String username = bufferedReader.readLine();
                String password = bufferedReader.readLine();
                Connection conn = DriverManager.getConnection(dblink, username, password);

                return conn;

            } catch (SQLException e) {
                e.printStackTrace();
                System.err.println("Unable to connect the DB!");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                System.err.println("Fail to read key.txt!");
            } catch (IOException e) {
                e.printStackTrace();
                System.err.println("Erro when read key.txt content!");
            }
        } catch (Exception x) {
            System.err.println("Unable to load the driver class!");
        }

        return null;
    }

    public static boolean tableExist(String tableName) throws SQLException {
        Connection connection = getConnection();
        java.sql.DatabaseMetaData metaData = connection.getMetaData();

        ResultSet tables = metaData.getTables(null, null, tableName, null);
        boolean isExist = tables.next();
        tables.close();

        return isExist;
    }
}
